package com.jshcbd.mvp_kt_demo.base.fragment

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.dylanc.viewbinding.base.inflateBindingWithGeneric
import com.jshcbd.mvp_kt_demo.base.mvp.BasePresenter
import com.trello.rxlifecycle2.components.support.RxFragment
import org.greenrobot.eventbus.EventBus

abstract class BaseFragment<VB : ViewBinding, P : BasePresenter<*, *>?> : RxFragment(), IFragment {
    var binding: VB? = null
    private val _binding: VB get() = binding!!
    protected var mPresenter: P? = null

    /*** View  */
    private var mRootView: View? = null

    /*** 上下文  */
    var mActivity: Activity? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mActivity = activity
        mPresenter = createPresenter()
        if (mRootView == null) {
            binding = inflateBindingWithGeneric(layoutInflater, container, false)
            mRootView = _binding.root
            initData(savedInstanceState)
        }

        val parent = mRootView!!.parent as ViewGroup
        parent.removeView(mRootView)
        //如果要使用 EventBus 请将此方法返回 true
        if (useEventBus()) {
            //注册 EventBus
            EventBus.getDefault().register(this)
        }
        return mRootView
    }

    protected abstract fun createPresenter(): P
    override fun onDestroyView() {
        super.onDestroyView()

        //如果要使用 EventBus 请将此方法返回 true
        if (useEventBus()) {
            //解除注册 EventBus
            EventBus.getDefault().unregister(this)
        }
        if (mPresenter != null) {
            mPresenter?.detachView()
        }
        binding = null
    }

    /**
     * 子类Activity要使用EventBus只需要重写此方法返回true即可
     *
     * @return
     */
    override fun useEventBus(): Boolean {
        return false
    }
}